package com.example.jetpacktest.coroutine

import kotlinx.coroutines.*
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import org.junit.Test
import java.util.concurrent.atomic.AtomicInteger

class Test006 {

    suspend fun f001(action: suspend () -> Unit){
        coroutineScope {
            repeat(100){
                launch {
                    repeat(1000){
                        action()
                    }
                }
            }
        }
    }

    /*@Volatile
    var count = 0*/

    //var count: AtomicInteger = AtomicInteger(0)

    var count = 0

    @Test
    fun test001(){
        runBlocking {
            val singContext = newSingleThreadContext("mySingleThreadContext")
            launch(Dispatchers.Default) {
                f001 {
                    withContext(singContext){
                        count++
                    }
                }
                println("count = $count")
            }
        }
    }


    @Test
    fun test002(){
        runBlocking {
            val mutex = Mutex()
            withContext (Dispatchers.Default){
                f001 {
                    mutex.withLock {
                        count++
                    }
                }
                println("count = $count")
            }
            //println("count = $count")
        }
    }


    @Test
    fun test003(){
        runBlocking {
            val x = coroutineScope {
                //delay(5000)
                repeat(10){
                    launch {
                        delay(10000)
                    }
                }
                13
            }
            println(x)
        }
    }


}